﻿//======================================================================
//
//        Copyright (C) 2015   
//        All rights reserved
//
//        filename : CardSeparate
//        description : 离盒操作编辑
//        created by XXX at  20150821
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using CardLogistics.Model.CardMaking;
using System.Data;


namespace CardLogistics.Web.MainPage.CardMaking.CardSeparate
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.CardMaking.CardMaking_CardSeparateData DAL = new CardLogistics.DAL.CardMaking.CardMaking_CardSeparateData();
        private static readonly CardLogistics.DAL.CardMaking.CardMaking_CardSeparateDetailData DDAL = new CardLogistics.DAL.CardMaking.CardMaking_CardSeparateDetailData();
        private static readonly DAL.CardRecordData cardRecordDal = new CardLogistics.DAL.CardRecordData();
        string separateId = "";//离盒操作Id
        string FileValue = ""; //离盒操作明细字段
        public string TitleName
        {
            get;
            set;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SEPARATEDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//操作日期
                SEPARATEUSER.Value = LoggedUser.USERFULLNAME;//操作人默认为当前登录用户
                InitControl();
            }
        }

        #region 编辑时绑定值
        /// <summary>
        /// 编辑时绑定值
        /// </summary>
        public void InitControl()
        {
            TitleName = GetStatusInfo(0, "离盒操作");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    CardMaking_CardSeparate pData = DAL.GetModel(_key);
                    SetWebControls(this.Page, pData);
                    DataTable dt = DDAL.GetInfoById(pData.ID);
                    string detId = "";
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            detId += dr["boxno"].ToString() + "|" + dr["cardno"].ToString() + "|" + dr["startno"].ToString() + "|" + dr["endno"].ToString() + "|" +
                                     dr["DueNumber"].ToString() + "|" + dr["actualnumber"].ToString() + "|" + dr["missingcardno"].ToString() + ";";
                        }
                        hf_separatId.Value = detId.TrimEnd(';');
                    }
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (pData.ISSUBMIT == 0 || pData.ISSUBMIT == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    TitleName = GetStatusInfo(int.Parse(pData.ISSUBMIT.ToString()), "离盒操作");
                }
            }
            else
            {
                SEPARATENO.Value = GetBillNumber("离盒操作");
            }

        }
        #endregion

        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
               
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }



        #region 提示信息
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(17, result.Split(',')[1]); //离盒操作
                    InsertLog("保存并提交离盒操作信息,离盒单号:" + SEPARATENO.Value);
                }
                else
                    InsertLog("保存离盒信息,离盒单号:" + SEPARATENO.Value);
                ReturnListInfo();
            }
            else if (result.Split(',')[0] == "-1")
            {
                //判断入库明细中起始卡号和结束卡号是否重复
                ShowMessageBox(result.Split(',')[1]);
            }
            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        /// <summary>
        /// 需求信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            string result = string.Empty;
            CardMaking_CardSeparate model = new CardMaking_CardSeparate();
            model = GetWebControls<CardMaking_CardSeparate>(this.Page);
            model.Separateno = SEPARATENO.Value; //操作单号
            model.Separatedate = DateTime.Now;
            model.LASTUPDATEUSER = LoggedUser.ID;
            model.LASTUPDATEDATE = DateTime.Now;
            model.Separateuser =SEPARATEUSER.Value;//操作人
            model.REMARKS = REMARKS.Value; //备注
            model.ISSUBMIT = issubmit;
            FileValue = hf_separatId.Value; //离盒操作明细字段
            separateId = model.ID;//获取离盒操作单ID

            #region 判断验收入库明细信息
            if (FileValue != "")
            {
                string[] detail = FileValue.Split(';');
                string message = "";//提示信息
                string boxNo = ""; //箱号
                string startNo = ""; //起始卡号
                string endNo = ""; //结束卡号
                int dueSum = 0;//　应有数量
                int actualNum = 0; //应有数量
                string missCardNo = ""; //缺失卡号
                string[] BoxCardNo = new string[detail.Length];//保存明细中的箱号盒号
                string[] StartCardNo = new string[detail.Length];//保存明细中的开始卡号
                //判断入库明细中起始卡号和结束卡号是否已存在
                for (int i = 0; i < detail.Length; i++)
                {
                    boxNo = detail[i].Split('|')[0].Trim();//箱号
                    startNo = detail[i].Split('|')[2].Trim();//起始卡号
                    endNo = detail[i].Split('|')[3].Trim();//结束卡号
                    dueSum = Convert.ToInt32(detail[i].Split('|')[4].Trim());//应有数量
                    actualNum = Convert.ToInt32(detail[i].Split('|')[5].Trim());//实际数量
                    missCardNo = detail[i].Split('|')[6].Trim().Trim(); //缺失卡号
                    string index = "第" + (i + 1) + "行";//提示明细行号
                    string StrSpId = "";//卡片验收入库ID
                    if (IsEdit)
                    {
                        StrSpId = Request.QueryString["Id"].ToString();
                    }
                    #region 判断明细中盒号是否重复
                    bool isExit = false;
                    string strCardNO = detail[i].Split('|')[1].Trim();//盒号
                    //判断明细中盒号是否录入重复
                    if (BoxCardNo != null)
                    {
                        isExit = BoxCardNo.Contains(strCardNO);
                        if (isExit)
                        {
                            message += index + "盒号录入重复！\n";
                        }
                    }
                    if (!isExit)
                    {
                        BoxCardNo[i] = strCardNO;
                    }
                    // 根据盒号判断是否在卡片验收入库单中已存在
                    bool strResult = cardRecordDal.IsExisRuKu(StrSpId, startNo, endNo);
                    if (!strResult)
                    {
                        message += index + "卡号范围在库中不存在！\n";
                    }
                    #endregion

                    #region 判断卡号是否重复
                    bool isCard = false;
                    //判断明细中开始卡号是否录入重复
                    if (StartCardNo != null)
                    {
                        isCard = StartCardNo.Contains(startNo);
                        if (isCard)
                        {
                            message += index + "卡号录入重复！\n";
                        }
                    }
                    if (!isCard)
                    {
                        StartCardNo[i] = startNo;
                    }
                    #endregion

                    #region 根据开始卡号、结束卡号判断是否在卡片验收入库单中已存在

                    bool IsExisSp = DAL.IsExisSpKu(StrSpId, startNo, endNo);
                    if (IsExisSp)
                    {
                        message += index + "卡号范围在库中已存在！\n";
                    }
                    #endregion

                    #region 循环判断每一个缺卡卡号长度是否为8位数字，并且在开始卡号和结束卡号之间；如果缺卡卡号为空，且实际数量小于等于应有数量时，则提示未录入缺卡卡号
                    if (missCardNo == "''")//缺卡卡号为空
                    {
                        if (actualNum < dueSum)//实际数量小于等于应有数量
                        {
                            message += index + "未录入缺卡卡号！\n";
                        }
                    }
                    else
                    {
                        //循环判断每一个缺卡卡号长度是否为8位数字，并且在开始卡号和结束卡号之间
                        string[] misNos = missCardNo.Split(',');//单个缺卡卡号
                        for (int j = 0; j < misNos.Length; j++)
                        {
                            string tempMis = misNos[j].Trim().Replace("'", "");
                            if (tempMis.Length != 8)//判断每一个缺卡卡号长度是否为8位数字
                            {
                                message += index + "缺卡卡号‘" + tempMis + "’位数输入有误！\n";
                            }
                            else
                            {
                                //判断缺卡卡号是否在开始卡号和结束卡号之间
                                if (int.Parse(tempMis) < int.Parse(startNo.Replace("'", "")) || int.Parse(tempMis) > int.Parse(endNo.Replace("'", "")))
                                {
                                    message += index + "缺卡卡号‘" + tempMis + "’已超出卡号范围！\n";
                                }
                            }
                        }
                    }
                    #endregion

                    #region 缺卡卡号有值时判断实际数量
                    if (missCardNo != "''")
                    {
                        int missNumber = missCardNo.Split(',').Length;//缺失卡号数量
                        int actualNumber = dueSum - missNumber;//实际数量=应有数量-缺失卡号数量
                        if (dueSum == actualNum || actualNum != actualNumber)
                        {
                            message += index +"实际数量输入有误！\n";
                        }
                    }
                    #endregion
                }
                if (message != "")
                {
                    return "-1," + message;
                }
            }
            #endregion
            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model, FileValue);
            }
            else
            {
                result = DAL.Add(model, FileValue);
                if (result.Split(',')[0] == "ok")
                {
                    ChgBillNumber("离盒操作");
                }
            }
            return result;
        }
    }
}